import React, {useEffect, useState} from 'react'
import {View, Text, Swiper, SwiperItem} from '@tarojs/components'
import {AtIcon, AtButton, AtNoticebar, AtModal} from "taro-ui";
import Taro, {useRouter, useReady,useShareAppMessage} from "@tarojs/taro";
import {PaperPo, PaperResultQuestionPo, QuestionPo} from "../../types";
import subjectStore from "../../store/subjectStore"
import {getEnv} from "../../env";
import {transTime, useInterval} from "../../util/util"
import CheckIsLogin from "../../components/CheckIsLogin";
import './index.scss'


// 判断正确
function checkRightOrWrong(question: QuestionPo): boolean {
  const rights = question.answer.split(",");
  return (rights.length === question.userAnswer?.length && rights.every(item => question.userAnswer?.find(q => q === item)))
}

export default CheckIsLogin(() => {
  const paperId = useRouter().params.paperId ?? 1;
  const initIndex = useRouter().params.initIndex ?? "0"; // 初始索引
  const analysis = useRouter().params.analysis ?? "" // 解析模式;
  const paperResultId = useRouter().params.paperResultId ?? "13" // 考试结果;
  const subjectId = subjectStore.useStore(state => state.current?.id)
  const [data, setData] = useState<PaperPo | null>(null)
  const [questions, setQuestions] = useState<QuestionPo[]>(() => [])
  const [index, setIndex] = useState(parseInt(initIndex));
  const [mOpen, setMOpen] = useState<boolean>(false)
  const [countDown, setCountDown] = useState<number>(-1)

  // 分享
  useShareAppMessage(() => {
    return {
      title: '考一考朋友',
      path: '/pages/index/index'
    }
  })

  // 初始化
  useReady(() => {
    const requestArr = [
      () => Taro.request({
        url: `${getEnv().baseUrl}/paper/${paperId}`,
        method: "GET"
      })
    ]
    if (analysis) {
      requestArr.push(() => Taro.request({
        url: `${getEnv().baseUrl}/paper/result/${paperResultId}`,
        method: "GET"
      }))
    }
    Promise.all(requestArr.map(item => item())).then(([paperData, paperResultData]) => {
      setData(paperData.data);
      setCountDown(() => paperData.data.time * 60)
      if (!paperResultData) return setQuestions(paperData.data.questions) // 考试模式在此结束
      // 解析模式开始
      paperResultData.data.questions = JSON.parse(paperResultData.data.questions);
      if (!!analysis) {
        setQuestions(() => {
          const qs = paperData.data.questions as QuestionPo[]
          const rqs = paperResultData.data.questions as PaperResultQuestionPo[]
          const rqws = rqs.filter(item => item.status === 0);
          return qs.filter(item => {
            if (analysis === "all") return true // 全部解析
            return !!rqws.find(i => i.questionId === item.id) //
          }).map(item => {
            const rq = rqs.find((rqi => rqi.questionId === item.id))
            return {
              ...item,
              viewAnalysis: true,
              userAnswer: rq!.userAnswer.split(",")
            }
          })
        })
      }
    })


    if (analysis === "all") {
      Taro.setNavigationBarTitle({title: "试卷解析"})
    }
    if (analysis === "wrong") {
      Taro.setNavigationBarTitle({title: "错题解析"})
    }
  })

  // 倒计时
  useInterval((id) => {
    if (!!analysis) return clearInterval(id) // 如果是解析模式直接退出
    if (countDown === -1) return;
    if (countDown < 0) return
    if (!countDown) {
      clearInterval(id);
      submit() // 自动交卷
      return;
    }
    setCountDown(c => c - 1)
  }, 1000)


  // 注册事件
  useEffect(() => {
    Taro.eventCenter.on("updateIndex", (newIndex: number) => setIndex(newIndex))
    return () => Taro.eventCenter.off("updateIndex")
  }, [])

  // 交卷
  async function submit() {
    const params = {
      paperId: data?.id,
      subjectId: subjectId,
      useTime: (data?.time ?? 0) * 60 - countDown,
      questions: questions.map((item) => {
        return {
          questionId: item.id,
          userAnswer: item.userAnswer ? item.userAnswer.join(",") : "",
          status: !item.userAnswer ? -1 : checkRightOrWrong(item) ? 1 : 0   // -1:未答 0：错误 1：正确
        }
      })
    }

    Taro.showLoading({mask: true, title: "交卷中"});
    const result = await Taro.request({
      url: `${getEnv().baseUrl}/paper/submit`,
      data: params,
      method: "POST"
    }).finally(() => Taro.hideLoading())
    // 跳转路由
    Taro.redirectTo({
      url: `/pages/testPaperResult/index?paperResultId=${result.data}&paperName=${data?.paperName}`
    })
  }

  if (!data) return null;
  return <View>
    <AtNoticebar customStyle={{textAlign: "center"}}>左右滑动切换题目{
      !analysis ? <Text className='count-down'>{transTime(countDown)}</Text> : null
    }</AtNoticebar>
    <View className='title wing-blank'>
      <View><Text>{data.paperName}</Text></View>
      <View className='title-right'><Text className='title-right-left'>{index + 1}</Text>/{questions?.length}
      </View>
    </View>
    <View className='content'>
      <Swiper className='swiper' skipHiddenItemLayout duration={100} easingFunction='easeOutCubic' current={index}
        onAnimationFinish={(e) => {
                console.log(e.detail.source);
                if (e.detail.source !== "touch") return
                if (index === e.detail.current) return;
                setIndex(e.detail.current);
              }}
      >
        {
          questions?.map((item, i) => {
            return <SwiperItem key={i} itemId={i.toString()}>
              <Question value={item} onAnswer={q => {
                setQuestions(qs => {
                  return qs.map((iq, ii) => {
                    if (ii === i) return q
                    return iq
                  }) as QuestionPo[];
                })
              }}
              />
            </SwiperItem>
          })
        }
      </Swiper>
    </View>
    {
      !analysis ? <View className='footer'>
        <View className='footer-item' onClick={() => {
          Taro.setStorageSync("currentQuestions", JSON.stringify(questions))
          Taro.navigateTo({
            url: "/pages/testPaperAnswerSheet/index",
            fail() {
              Taro.removeStorageSync("currentQuestions")
            }
          })
        }}
        >
          <AtIcon value='file-code' size='24' color='#848891' />
          <Text>题卡</Text>
        </View>
        <View className='footer-item' onClick={() => {
          setQuestions((qs) => {
            return qs.map((ii, iii) => {
              if (iii === index) {
                return {
                  ...ii,
                  viewAnalysis: true
                }
              }
              return ii
            }) as QuestionPo[]
          })
        }}
        >
          <AtIcon value='help' size='24' color='#848891' />
          <Text>答案</Text>
        </View>
        <View className='footer-item'>
          <AtIcon value='upload' size='24' color='#848891' onClick={() => {
            const noUserAnswerQuestions = questions.filter(item => !item.userAnswer)
            if (noUserAnswerQuestions.length) {
              return setMOpen(true)
            }
            submit()
          }}
          />
          <Text>交卷</Text>
        </View>

      </View> : null
    }
    {/*  model*/}
    <AtModal
      isOpened={mOpen}
      title='交卷确认'
      cancelText='取消'
      confirmText='确认'
      onClose={() => setMOpen(false)}
      onCancel={() => setMOpen(false)}
      onConfirm={() => {
        submit().finally(() => setMOpen(false))
      }
      }
      content='您的题目还没有答完，确定要交卷吗？'
    />
  </View>
})

// 题目
interface QuestionProps {
  value: QuestionPo,
  onAnswer: (question: QuestionPo) => void
}

type ZiMu = "A" | "B" | "C" | "D" | "E" | "F" | "G"

type OptionPo = Record<ZiMu, string>


const QuestionInstance = ({value: question, onAnswer}: QuestionProps) => {
  // const [question, setQuestion] = useState(questionProp);
  const options = JSON.parse(question.options) as OptionPo

  function onSelect(value) {
    if (question.viewAnalysis) return;
    if (question.type === 1) { // 单选题
      const userAnswer = [value]
      onAnswer({
        ...question,
        userAnswer
      })
      // setQuestion(q => ({...q, userAnswer}))
    }
    if (question.type === 2) { // 多选题
      let e = question.userAnswer ?? [];
      if (e.find(item => item === value)) {
        e = e.filter(item => item !== value)
      } else {
        e.push(value)
      }
      const userAnswer = e
      // setQuestion(q => ({...q, userAnswer}))
      onAnswer({
        ...question,
        userAnswer
      })
    }
  }

  // 获取选项状态
  function getStatusByUserAnswer(k: ZiMu): OptionStatus | undefined {
    const userAnswer = question.userAnswer ?? []
    if (userAnswer.find(item => item === k)) {
      return OptionStatus.SELECT
    }
  }


  // 解析选项状态
  function getStatusWithViewAnalysis(k: ZiMu): OptionStatus | undefined {
    const rights = question.answer.split(",");
    if (rights.find(item => item === k)) {
      return OptionStatus.RIGHT
    } else if (question.userAnswer?.find(item => item === k)) {
      return OptionStatus.WRONG
    }
  }


  return <View className='swiper-item wing-blank wing-space'>
    <View className='subject-title'>{question.type == 1 ? "单选题" : "多选题"}</View>
    <View className='subject-content'>
      {question.stem}
    </View>
    <View className='subject-answer'>
      {
        Object.keys(options).map((k, index) => {
          return <Option key={index} l={k as ZiMu} r={options[k]} onSelect={onSelect}
            status={question.viewAnalysis ? getStatusWithViewAnalysis(k as ZiMu) : getStatusByUserAnswer(k as ZiMu)}
          />
        })
      }
    </View>
    {/*  解析*/}
    {
      question.viewAnalysis ? <View style={{paddingBottom: "20px", paddingTop: "30px"}}>
        <View className='subject-analysis'>
          <View className='subject-analysis-title'>
            {
              checkRightOrWrong(question) ? <View className='tag-right'>回答正确</View> :
                <View className='tag-wrong'>回答错误</View>
            }
            <View className='subject-analysis-title-r'>
              {/*<AtButton size='small' circle full={false}>本题纠错</AtButton>*/}
              <AtButton size='small' circle full={false} 	openType='share'>考考朋友</AtButton>
            </View>
          </View>
          <View className='subject-analysis-subtitle'>
            <View className='subject-analysis-subtitle-box'>
              <Text>正确答案</Text>
              <Text className='subject-analysis-subtitle-box-t'>{question.answer}</Text>
            </View>
            <View className='subject-analysis-subtitle-d' />
            <View className='subject-analysis-subtitle-box'>
              <Text>你的答案</Text>
              <Text
                className='subject-analysis-subtitle-box-t'
              >{question.userAnswer && question.userAnswer.length ? question.userAnswer?.join(",") : "空"}</Text>
            </View>
          </View>
          <View className='subject-analysis-content'>
            <View className='subject-analysis-content-title'>[参考解析]</View>
            <View>{question.analysis}</View>
          </View>
        </View>
      </View> : null
    }
  </View>
}

const Question = React.memo(QuestionInstance, (prev, next) => {
  // console.log(prev.value === next.value);
  return (prev.value === next.value);
  // return prev.value.userAnswer !==next.value.userAnswer
})
// const Question = QuestionInstance


// 选项
enum OptionStatus {
  SELECT,
  RIGHT,
  WRONG
}


interface OptionProps {
  status?: OptionStatus,
  l: ZiMu,
  r: string,

  onSelect(v: ZiMu)
}

const Option = (props: OptionProps) => {
  let className = "wing-blank subject-option ";
  if (props.status === OptionStatus.SELECT) className = className + "subject-option-select"
  if (props.status === OptionStatus.RIGHT) className = className + "subject-option-right"
  if (props.status === OptionStatus.WRONG) className = className + "subject-option-wrong"

  // 渲染左面
  function renderLeft() {
    if (props.status === OptionStatus.RIGHT) {
      return <View className='subject-option-l'><AtIcon value='check' size='18' color='#fff' /></View>
    }
    if (props.status === OptionStatus.WRONG) {
      return <View className='subject-option-l'><AtIcon value='close' size='18' color='#fff' /></View>
    }
    return <View className='subject-option-l'>{props.l}.</View>
  }

  return <View className={className} onClick={() => props.onSelect(props.l)}>
    {renderLeft()}
    <Text>{props.r}</Text>
  </View>
}

